var pageBean = null;
var dataList = {};
var cities = {};
var spaces = {};
var processPersons = {};
var currentData = null;

$(document).ready(function(e) {	
	
	$("#btnClean").click(clean);
	$("#btnBack").click(backDataList);
    $("#btnCancleContractProduct").click(backDataList);
    $("#btnCancleContractDetail").click(backDataList);


	initialSpace();//加载和初始化空间信息选择
	initialClient();//初始化客户
	initialSelect();
	$(".table tr[name='No1']").show();
	$(".table tr[name='No2']").hide();
	
	$("#btn-progress").click(function(){
		$name =$("#y_orderusername").val();
		if(!$name){
			alert("客户名称不能为空");
			return false;
		}else{
			$("#infoTitle").text($name+'-新建订单');
			
			$(".table tr[name='No2']").show();
			$(".table tr[name='No1']").hide();	
		}

	})
	
	$("#btn-save").click(btnsave);
	

});
//新建保存
function btnsave(){
   var clientName = $("#y_orderusername").val(),
    orderName =$("#y_ordername").val(),
    orderAmount = $("#y_ordermoney").val(),
    validTime =$("#y_ordertime").val(),
    orderMark =$("#y_remark").val(),
    orderType =$("#y_type").val();
    
   if(!clientName){
	   alert("请输入客户！");return false;
   }
   if(!orderName){
	   alert("请输入订单名称！");return false;
   }
   if(!orderAmount){
	   alert("请输入订单金额！");return false;
   }
   if(!validTime){
	   alert("请选择订单日期！");return false;
   }
   if(!orderType){
	   alert("请选择订单类型！");return false;
   }
   json_data={'clientName':clientName,'orderName':orderName,'orderAmount':orderAmount,'validTime':validTime,'orderType':orderType,'orderMark':orderMark};
   $.ajax({
       url: '/euc/temporaryOrder/save',
       data:JSON.stringify(json_data),
       beforeSend: function(request) {
       	var accessToken = localStorage.getItem('accessToken');
           request.setRequestHeader("accessToken",accessToken );
       },
       dataType: 'JSON',
       async: true,
       contentType:'application/json;charset=utf-8',
       type: 'POST',
       success: function (result, textStatus, response) {
    	   	if(result.status==0){
    	   		alert("新增临时订单成功");
    	   		$("#addModal").modal('hide');
    	   		//页面重新获取
                search(1);
    	   	}else{
    	   		alert(result.message);
    	   	}
       },
       error: function () {
       	/*alert("error");*/
       }  
   });

}

function initialSpace(){//初始化空间信息
	try{
		var spaceString = localStorage.getItem('space');
		return spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}
function initialClient(){
	var clientSelect = '#y_orderusername';
    
        var clientString = localStorage.getItem('client');
        if(clientString){
        	clients = $.parseJSON(clientString);
            $.each(clients,function(index,data){

                $('<option value="'+ (data.companyName != ''?data.companyName:data.memberName)
                    +'">'+ (data.companyName != ''?data.companyName:data.memberName) +'</option>').appendTo($(clientSelect));
            });
            
            return true;
        }
            
    
    $.ajax({
        url: '/euc/client/list',
        data:'',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
           //var clientSelect = $("#client_id");
            try{
                $.each(result,function(index,data){

                        $('<option value="'+ (data.companyName != ''?data.companyName:data.memberName)
                            +'">'+ (data.companyName != ''?data.companyName:data.memberName) +'</option>').appendTo($(clientSelect));
                });
               // console.log(clients);
                var clientJson = JSON.stringify(clients);
                localStorage.setItem('client',clientJson);
            }catch(e){
                console.log(e.message);
            }
        },
        error: function () {
            /*alert("error");*/
        }
    });
}

function backDataList(){	
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
    $("DIV[name='contractForm']").hide();
}

function clean(){	
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).val(0).trigger('change');
	$('input[name="searchTimeStart"]').val(getNowFormatDate());
	$('input[name="searchTimeEnd"]').val(getNowFormatDate());
	$('.scinput').val('');
}

function initialSelect(){
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected="">请选择</option>').appendTo($(spaceSelect));
	$.each(spaces,function(key,space){	
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
	});
	$(spaceSelect).val(0).trigger('change');
}

function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}


function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
    $("DIV[name='contractForm']").hide();
}




function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function getSearchParameter(currentPage){
	try{
		var clientName = $("INPUT[name='parameter']").val();	
		var spaceId = $("#searchSpace").val();
		if(spaceId == '0'){
			spaceId = '';
		}		
		var searchTimeStart = $("#searchTimeStart").val();
		var searchTimeEnd = $("#searchTimeEnd").val();
		
		var requestJson = {currentPage:currentPage,data:{'spaceId':spaceId,'clientName':clientName,'startTime':searchTimeStart,'endTime':searchTimeEnd}};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}

function search(currentPage){
	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}

	$.ajax({
        url: '/euc/temporaryOrder/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {

        	pageBean = result.data;
        	$("#orderTable").empty();	        	
        	$.each(result.data.list,function(i,data){

        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
      		
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + $.trim(data["orderNumber"]) + '</td>';
        		html += '<td>' + $.trim(data["spaceName"]) + '</td>';
        		html += '<td>' + $.trim(data["clientName"]) + '</td>';
        		html += '<td>' + $.trim(data["orderName"]) + '</td>';
                html += '<td>' + $.trim(data["orderAmount"]) + '</td>';
                html += '<td>' + $.trim(data["createdBy"]) + '</td>';
        		html += '<td>' + $.trim(data["createTime"]) + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">查看</a>&nbsp;&nbsp;&nbsp;</td>';
        		html += '</tr>';
	        	$("#orderTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log('/euc/order/queryseatorder error');
        }  
    });
}

function detail(id){//查看订单
	
	$.ajax({
        url: '/euc/temporaryOrder/detail',
        data:{"id":id},
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'GET',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	//var clientLevle = $("SELECT[name='clientLevle']");   
        	data=result.data;
        	$("#detaillist").html('');
        	var html ='<tr><td>订单编号：'+data["orderNumber"]+'</td>';
        		html += '<td>订单类型：'+data["orderType"]+'</td></tr>';
        		html +='<tr><td>订单名称：'+data["orderName"]+'</td>';
        		html += '<td>订单总额：'+data["orderAmount"]+'</td></tr>';
        		html +='<tr><td>录入人：'+data["createdBy"]+'</td>';
        		html += '<td>订单创建时间：'+data["createTime"]+'</td></tr>';
        		html +='<tr><td>空间：'+data["spaceName"]+'</td>';
        		html += '<td>订单日期：'+data["validTime"]+'</td></tr>';
        		html +='<tr><td>客户名称：'+data["clientName"]+'</td>';
        		html += '<td>回款状态：'+(data['orderStatus']==0 ? '待回款' :'')+(data['orderStatus']==1 ? '已回款' :'')+'</td></tr>';
        		html +='<tr><td colspan=2>备注：'+data["orderMark"]+'</td></tr>';
        		$("#detaillist").append(html);
        		
        		$("#ViewModal").modal({
        			'show':true,
        			'backdrop':'static'
        		});
   			
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	
	
	
	
	
}

function checkPrice(e) { 
    var re = /^\d+(?=\.{0,1}\d+$|$)/ 
    if (e.value != "") { 
        if (!re.test(e.value)) { 
            alert("请输入正确的价格"); 
            e.value = ""; 
            e.focus(); 
        } 
    } 
} 
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

